﻿using System.IO;
using System.Text;
namespace LVYAN.Utils
{
    /// <summary>
    /// 
    /// </summary>
    public class JsonToModelService
    {
        public static string GetDataByPath(string path)
        {
            try
            {
                var filePath = Path.GetFullPath(path);
                string directoryName = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                if (!File.Exists(filePath))
                {
                    return "";
                }
                StreamReader streamReader = new StreamReader(filePath, Encoding.UTF8);
                string data = streamReader.ReadToEnd();
                streamReader.Close();
                streamReader.Dispose();
                return data;
            }
            catch (System.Exception x)
            {
                return "";
            }
        }

        public static T GetModelByPath<T>(string path)
        {
            var data = GetDataByPath(path);
            if (string.IsNullOrWhiteSpace(data)) return default;

            return JsonService.ToModel<T>(data);
        }
        public static void SetModelByPath<T>(string path, T t)
        {
            try
            {
                var filePath = Path.GetFullPath(path);
                string directoryName = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                var content = JsonService.ToString(t);
                FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                //获得字节数组
                byte[] data = System.Text.Encoding.Default.GetBytes(content);
                //开始写入
                fs.Write(data, 0, data.Length);
                //清空缓冲区、关闭流
                fs.Flush();
                fs.Close();
            }
            catch (System.Exception x)
            {
               
            }
        }

    }
}